﻿using System;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

namespace GeneralTool.CoreLibrary.WPFHelper.WPFControls
{
    /// <summary>
    /// 自动分割行列的表格
    /// </summary>
    public class AutoGrid : Grid
    {
        public static readonly DependencyProperty GridRowProperty = DependencyProperty.Register(nameof(GridRow), typeof(string), typeof(AutoGrid), new PropertyMetadata(GridRowChangedMethod));

        private static readonly char[] spliteCharArr = new char[] { ' ', ',', '，', '|' };
        private static void GridRowChangedMethod(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is AutoGrid g)
            {
                var str = e.NewValue + "";
                g.RowDefinitions.Clear();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    var arr = str.Split(spliteCharArr, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < arr.Length; i++)
                    {
                        var c = arr[i];
                        if (c.Equals("auto", StringComparison.OrdinalIgnoreCase))
                        {
                            g.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                        }
                        else if (double.TryParse(c, out var val))
                        {
                            g.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(val) });
                        }
                        else if (c.Equals("*", StringComparison.OrdinalIgnoreCase))
                        {
                            g.RowDefinitions.Add(new RowDefinition() { Height = new GridLength() });
                        }
                        else
                        {
                            if (TryGetLeadingNumber(c, out val))
                            {
                                g.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(val, GridUnitType.Star) });
                            }
                        }
                    }
                }
            }
        }

        static bool TryGetLeadingNumber(string input, out double number)
        {
            number = 0;
            // 定义正则表达式模式，用于匹配字符串开头的数值
            string pattern = @"^[+-]?\d*\.?\d+";
            Match match = Regex.Match(input, pattern);
            if (match.Success && double.TryParse(match.Value, out number))
            {
                return true;
            }
            return false;
        }

        public string GridRow
        {
            get => this.GetValue(GridRowProperty) + "";
            set => this.SetValue(GridRowProperty, value);
        }

        public static readonly DependencyProperty GridColProperty = DependencyProperty.Register(nameof(GridCol), typeof(string), typeof(AutoGrid), new PropertyMetadata(GridColChangedMethod));

        private static void GridColChangedMethod(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is AutoGrid g)
            {
                var str = e.NewValue + "";
                g.ColumnDefinitions.Clear();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    var arr = str.Split(spliteCharArr, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < arr.Length; i++)
                    {
                        var c = arr[i];
                        if (c.Equals("auto", StringComparison.OrdinalIgnoreCase))
                        {
                            g.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                        }
                        else if (double.TryParse(c, out var val))
                        {
                            g.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(val) });
                        }
                        else if (c.Equals("*", StringComparison.OrdinalIgnoreCase))
                        {
                            g.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                        }
                        else
                        {
                            if (TryGetLeadingNumber(c, out val))
                            {
                                g.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(val, GridUnitType.Star) });
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 分配 ColumnDefinitions 属性,以空格或,号分割
        /// </summary>
        public string GridCol
        {
            get => this.GetValue(GridColProperty) + "";
            set => this.SetValue(GridColProperty, value);
        }

        /// <summary>
        /// 是否自动分配控件的行列
        /// </summary>
        public bool AutoControlGrid
        {
            get => (bool)this.GetValue(AutoControlGridProperty);
            set => this.SetValue(AutoControlGridProperty, value);
        }

        public static readonly DependencyProperty AutoControlGridProperty = DependencyProperty.Register(nameof(AutoControlGrid), typeof(bool), typeof(AutoGrid), new PropertyMetadata(AutoControlGridChanged));

        private static void AutoControlGridChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is AutoGrid g)
            {
                g.OnInitialized(new EventArgs());
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            this.ChildrenArrary();
        }

        private void ChildrenArrary()
        {
            var controls = this.Children;
            var columnCount = this.ColumnDefinitions.Count;

            var colIndex = 0;
            var rowIndex = 0;
            for (int i = 0; i < controls.Count; i++)
            {
                var curr = controls[i];
                if (i + 1 == columnCount)
                {
                    colIndex = 0;
                    rowIndex++;
                }

                curr.SetValue(Grid.RowProperty, rowIndex);
                curr.SetValue(Grid.ColumnProperty, colIndex);
                colIndex++;
            }
        }
    }
}
